package cn.mengfly.testnrz.netty.encoder;

import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.MessageToMessageEncoder;

import java.util.List;

/**
 * @author Mengfly
 */
public class String2IntegerEncoder extends MessageToMessageEncoder<String> {

    @Override
    protected void encode(ChannelHandlerContext ctx, String msg, List<Object> out) throws Exception {
        char[] array = msg.toCharArray();
        for (char c : array) {
            if (c >= 48 && c <= 57) {
                out.add((int) c);
            }
        }
    }

    public static void main(String[] args) {
        ChannelInitializer<EmbeddedChannel> ri = new ChannelInitializer<EmbeddedChannel>() {
            @Override
            protected void initChannel(EmbeddedChannel ch) {
                ch.pipeline().addLast(new MessageToByteEncoderTest.Integer2ByteEncoder());
//                ch.pipeline().addLast(new String2IntegerEncoder());
            }
        };
        EmbeddedChannel channel = new EmbeddedChannel(ri);
        for (int i = 0; i < 100; i++) {
            String msg = "Hello This num is " + i;
            channel.write(msg);
        }
        channel.flush();
        ByteBuf buf = channel.readOutbound();
        while (buf != null) {
            System.out.println(buf.readInt());
            buf = channel.readOutbound();
        }
    }

}
